﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Sockets;
using System.Net;
using Intorise.Library.Common;
using System.Threading.Tasks;
using System.Threading;
using Intorise.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using RemoteControlModel;
using System.Net.NetworkInformation;

/// <summary>
///Manager 的摘要说明
/// </summary>
public class Manager
{
    static List<BotClient> clients = new List<BotClient>();

    static AsyncCallback acceptCallback = null;
    static NetTools net = new NetTools(60);
    static TcpListener listener = null;
    static List<StoreInfo> stores = new List<StoreInfo>();

    public Manager()
    {

    }

    public static void Init()
    {
        acceptCallback = callbackMethod;
        listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 520);
        listener.Start();
        listener.BeginAcceptTcpClient(acceptCallback, listener);
        Logs.Log("开始监听：127.0.0.1:520");
    }

    public static List<BotClient> BotClients { get { return clients; } }

    public static void RefreshBotClient()
    {
        lock (BotClients)
        {
            for (var i = 0; i < BotClients.Count; i++)
            {
                var client = BotClients[i];
                try
                {
                    var msg = new ReportMessage();
                    var data = msg.Serialize();
                    client.TcpClient.GetStream().Write(data, 0, data.Length);//判断是否已经断开
                }
                catch (Exception ex)
                {

                }
                client.Connected = client.TcpClient.Connected;
                if (!client.Connected)
                {
                    client.TcpClient.Close();
                    BotClients.RemoveAt(i--);
                }
            }
        }
    }

    public static bool RebootClient(Guid id)
    {
        lock (BotClients)
        {
            var client = BotClients.FirstOrDefault(f => f.ID == id);
            if (client == null)
            {
                return false;
            }

            try
            {
                var data = new RebootMessage().Serialize();
                client.TcpClient.GetStream().Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                Logs.HandleException(ex);
                return false;
            }
        }

        return true;
    }

    public static List<StoreInfo> Stores { get { return stores; } }

    private static void callbackMethod(IAsyncResult result)
    {
        TcpListener listener = (TcpListener)result.AsyncState;
        listener.BeginAcceptTcpClient(acceptCallback, listener);

        var client = new BotClient(listener.EndAcceptTcpClient(result));
        Logs.Log("收到新的连接来自：" + client.TcpClient.Client.RemoteEndPoint);

        lock (BotClients)
        {
            clients.Add(client);
        }

        ManualResetEvent eventer = new ManualResetEvent(false);
        Task.Factory.StartNew((obj) =>
        {
            var message = ReadMessage(((BotClient)obj).TcpClient.GetStream());
            if (message != null && message.MessageType == MessageTypeEnum.Register)
            {
                client.Name = ((RegisterMessage)message).ClientName;
                eventer.Set();
            }
        }, client);

        if (eventer.WaitOne(1000 * 60))
        {
            client.Connected = true;
            Logs.Log("收到客户注册消息");
        }
        else
        {
            Logs.Log("读取客户注册消息超时");
        }

        Task.Factory.StartNew((obj) =>
        {
            BotClient bot = (BotClient)obj;
            while (bot.Connected)
            {
                try
                {
                    var msg = ReadMessage(bot.TcpClient.GetStream());
                    if (msg == null)
                    {
                        continue;
                    }

                    switch (msg.MessageType)
                    {
                        case MessageTypeEnum.CommandResult:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    Logs.HandleException(ex);
                }
            }
            Logs.Log(bot.Name + "已经断开连接.");
        }, client);



    }

    private static void readDataMethod(object o)
    {

    }

    private static Message ReadMessage(NetworkStream stream)
    {
        BinaryFormatter formater = new BinaryFormatter();
        byte[] buffer = new byte[102400];

        int length = stream.Read(buffer, 0, 4);//读取4个字节为接下来的数据包的长度
        if (length < 4)
        {
            Logs.Log("读取数据异常，length < 4");
            return null;
        }

        var packgetLength = net.GetHostInt32(buffer, 0);
        if (packgetLength > buffer.Length)
        {
            buffer = new byte[packgetLength];
        }
        length = stream.Read(buffer, 0, packgetLength);
        if (length != packgetLength)
        {
            Logs.Log("读取数据异常，length!=packgetLength"); return null;
        }

        Message message = null;

        try
        {
            using (MemoryStream memory = new MemoryStream(buffer, 0, packgetLength))
            {
                message = (Message)formater.Deserialize(memory);
            }
        }
        catch (Exception ex)
        {
            Logs.HandleException(ex);
        }

        if (message == null)
        {
            Logs.Log("反序列化Message失败！");
        }
        return message;
    }

    private static void WriteMessage(NetworkStream stream, Message message)
    {
        BinaryFormatter formater = new BinaryFormatter();
        formater.Serialize(stream, message);
        stream.Flush();
    }
}